var Data = require('/src/modules/data.js');
require('/src/components/ajaxFileUpload.js');
var uploadimg = require('/src/vue/uploadimg/index.js');
// var ConfigCard = require('./modules/configCard/index.js');
var gameConfig = JSON.parse(sessionStorage.getItem('gameconfig'));

window.schemaJSON={
      bgimg:{
        style:{
          "background-color":"#eec495",
          "background-image": '//static.dev.adbaitai.com:8081/banner.png'
        }
      },
      jpico: {
        attr: {
          "src":"//static.dev.adbaitai.com:8081/jpico.png"
        }
      },
    mItems: {
        style: {
            "background-color":"#eec495"
        }
    },
      goodsImgOne: {
        style:{
          "background-image": '//static.dev.adbaitai.com:8081/egg.png'
        }
      },
      goodsImgTwo: {
        style:{
          "background-image": '//static.dev.adbaitai.com:8081/egg.png'
        }
      },
      goodsImgThree: {
        style:{
          "background-image": '//static.dev.adbaitai.com:8081/egg.png'
        }
      },
      goodsImgFour: {
        style:{
          "background-image": '//static.dev.adbaitai.com:8081/egg.png'
        }
      },
      goodsImgFive: {
        style:{
          "background-image": '//static.dev.adbaitai.com:8081/egg.png'
        }
      },
      goodsImgSix: {
        style:{
          "background-image": '//static.dev.adbaitai.com:8081/egg.png'
        }
      },
      statement:{
        style:{
          "color":"blue",
          "font-size":"1rem"
        },
        other:{
          innerHTML:"测试文案"
        }
      },
      goodList: {
        goodsItem1: {
          style: {
            "background-image": '//static.dev.adbaitai.com:8081/egg.png'
          },
          other: {
            innerHTML: "现金红包1"
          }
        }
      }
  };

new Vue({
    el: '#wrapper',
    components:{
      // configcard: ConfigCard
      uploadimg:uploadimg
    },
    data:{
      schemaJSON: window.schemaJSON,
      pageObj:'',
      example: '',
      activeCard: '',
      frameWindow: '',
      showCard: false,
      hex: '',
      bannerUrl: '',
    },
    watch: {
      'hex': function() {
      }
    },
    beforeCreate:function(){
    },
    mounted: function() {
        var _this = this;
       this.bindEvent();
       page.addEventListener('load',function(){

        //iframe onload后
         _this.page = document.body.querySelector('#page');
         _this.example = $(page.contentDocument);
         _this.frameWindow = page.contentWindow;
         _this.createDom('.J_schema');
        //显示configCard
         _this.showCard = true;
           _this.frameWindow.sendMessage('themeEgg.editItems.render',gameConfig.prizes);
       });
    },
    methods:{
      listenmsgfromchild:function(src){
          this.$emit('listenmsgfromchild',src);
          console.log(this.activeCard);
          this.setMaterialConfig(src);
      },
      // 初始化素材配置
      initMaterialConfig: function () {

      },
      createDom: function(obj) {
        var htmlStr = '';
        this.example.find(obj).each(function(index, item){
          if($(item).attr('data-type') === 'goodList') {
            // console.log(item)
            return;
          }else {

          }
            var dataSchema = JSON.parse($(item).attr('data-schema')),
                itemId = $(item).attr('data-id');
                
                Object.keys(dataSchema).forEach(function(schemaKey){
                  
                   Object.keys(dataSchema[schemaKey]).forEach(function(key){
                    //  console.log(this.schemaJSON[itemId][schemaKey][key])
                    var itemData = this.schemaJSON[itemId][schemaKey][key],
                        itemTitle = dataSchema[schemaKey][key][1],
                        itemType = dataSchema[schemaKey][key][0];
                    
                    if(itemType === 'IMG') {
                      //图片
                      htmlStr += '<li data-class="' + itemId + '" data-type="'+ itemType +'" data-action="'+ key +'" data-detail="'+ schemaKey +'">' +
                                    '<div><img src="' + itemData + '"/></div>' +
                                    '<span>' + itemTitle + '</span>' +
                                  '</li>';
                    }else {
                      htmlStr += '<li data-class="' + itemId + '" data-type="'+ itemType +'" data-action="'+ key +'" data-detail="'+ schemaKey +'">' +
                                    '<div style="'+ key +':'+ itemData +'"></div>' +
                                    '<span>' + itemTitle + '</span>' +
                                  '</li>';
                    }
                  });
                });
              
        });
        $('.J-configWrap').html(htmlStr);
      },
      bindEvent: function() {
        var _this = this;
        $(document).on('click', '.J-configWrap > li', function () { // 可编辑元素切换
          var $this = $(this);
          if (!$this.hasClass('active')) {
            $this
            .addClass('active')
            .siblings().removeClass('active')
            // 当前正在编辑的card
            _this.activeCard = this;
            _this.changeEditOption($this);
          }

        }).on('change', '.J-gameUploadBtn', function () { // 修改图片素材类型 src, background-image
            var url = 'http://static.adbaitai.com/game/dzp/startBtn.png';
            // $('.J-previewImgUpload').attr('src', 'http://static.adbaitai.com/game/dzp/startBtn.png');
            // return;
            var gameUploadBtn = $('.J-gameUploadBtn');
            gameUploadBtn.attr('id', 'J-gameUploadBtn')

            _this.ajaxImageUpload('J-gameUploadBtn');

          }).on('click', '#colorSureBtn', function(){
            // 选择颜色
            var redValue = $('[data-topic=red]>input').val(),
                greenValue = $('[data-topic=green]>input').val(),
                blueValue = $('[data-topic=blue]>input').val(),
                alphaValue = $('[data-topic=alpha]>input').val(),
                resultColor = 'rgba('+redValue+','+greenValue+','+blueValue+','+alphaValue+')';
            _this.setMaterialConfig(resultColor);
          });

      },
      // 图片上传
      ajaxImageUpload: function (fileElementId) {
        var _this = this;
        Data.upLoadImg(fileElementId, function(data){
          console.log(data);
        });
        // $.ajaxFileUpload({
        //   url: _this.hostName() + '/fileUpload/ajaxImageUpload.action',
        //   secureuri: false,
        //   fileElementId: fileElementId,
        //   dataType: 'json',
        //   success: function (data, status) {
        //     if (data.success) {
        //       var url = data.data.url + data.data.bucketName
        //       console.log('upload success:' + url)
        //       callback(url)
        //     }
        //   },
        //   error: function (error) {
        //     console.log(error)
        //   }
        // })

      },
      setMaterialConfig: function(hex) {
        var itemId = $(this.activeCard).attr('data-class'),
            key = $(this.activeCard).attr('data-action'),
            dataType = $(this.activeCard).attr('data-type'),
            dataDetail = $(this.activeCard).attr('data-detail'),
            type = '';
        //改变颜色
        this.hex = hex;
          if(dataType === 'IMG') {
            $(this.activeCard).children('div').find('img').attr("src", hex);
          }else {
            $(this.activeCard).children('div').css(key, hex);
          }
        
        schemaJSON[itemId][dataDetail][key] = hex;
        this.frameWindow.sendMessage('schemaJSON',schemaJSON);
      },
      changeEditOption: function (e) {
          this.activeElement = e;
          var previewImgUpload = $('.J-previewImgUpload'),
              imgSrc = $(e).find('img').attr('src'),
              colorPicker = $('.J-colorPicker'),
              type = $(e).attr('data-type'),
              imgUpload = $('.J-imgUpload');

          $('#J_size').html('')
          imgUpload.hide();
          colorPicker.hide();

          if (type.indexOf('IMG')> -1) {
            this.bannerUrl = imgSrc;
            imgUpload.show()
            previewImgUpload.attr('src', imgSrc)


            if ($(e).attr('data-size')) {
              $('#J_size').html('尺寸：' + $(e).attr('data-size') + 'px');
            }

          }

          if (type.indexOf('COLOR') > -1) {

            colorPicker.show()

          }

        }
    }
});
